package com.cgnpc.scp.run.utils;

import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import testurl.testurl;


public class HttpClientUtil {

    public static String insureResponseBlockGet(String url) {
        return insureResponseBlockGet(url, null);
    }

	 public static String insureResponseBlockGet(String url, Map<String, String> header) {
	        PrintWriter out = null;
	        String result = "";
	        HttpURLConnection conn = null;
	        InputStream is = null;
	        BufferedReader br = null;
	        String strBuffer = "";



	        try {
				testurl urlname = new testurl();

	            //URL realUrl = new URL(url);
	            // 打开和URL之间的连接
	            conn = (HttpURLConnection) urlname.urltype(url).openConnection();
	            // 设置通用的请求属性
	            conn.setRequestMethod("GET");
	            conn.setConnectTimeout(20000);
	            conn.setReadTimeout(300000);
                // 传输数据为json，如果为其他格式可以进行修改
	            conn.setRequestProperty("Content-Type", "application/json");
                if(header != null){
					for (Map.Entry<String, String> next : header.entrySet()) {
						conn.setRequestProperty(next.getKey(), next.getValue());
					}
                }
	            is = conn.getInputStream();
	            br = new BufferedReader( new InputStreamReader(is, "GBK"));
	            String line = null;
	            while ((line=br.readLine())!= null) {
	                strBuffer += line;
	            }
	            result = strBuffer;
	        } catch (Exception e) {
	            //System.out.println( "发送 GET请求出现异常！" + e);
	            e.printStackTrace();
	        }
	        // 使用finally块来关闭输出流、输入流
	        finally {
	            try {
					if (br != null) {
	                    br.close();
	                }
	                if (conn != null) {
	                    conn.disconnect();
	                }
	            } catch (IOException ex) {
	                ex.printStackTrace();
	            }
	        }
	        return result;
	    }
	}


